package com.scut.edu.wanyou.channel;


import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.w3c.dom.ls.LSInput;

import com.scut.edu.wanyou.LoginActivity;
import com.scut.edu.wanyou.MainActivity;
import com.scut.edu.wanyou.R;
import com.scut.edu.wanyou.conf.Config;
import com.scut.edu.wanyou.home.GalleryAdapter;
import com.scut.edu.wanyou.net.HttpTask;
import com.scut.edu.wanyou.net.WYParams;
import com.scut.edu.wanyou.util.Parser;
import com.scut.edu.wanyou.util.UserKeeper;
import com.scut.edu.wanyou.util.UserToken;
import com.scut.edu.wanyou.util.WYRequestListener;
import com.scut.edu.wanyou.widget.FlowIndicator;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class ChannelActivity extends Activity {
	
	private ListView act_list = null;
	
	private Gallery mGallery = null;
    private GalleryAdapter mGalleryAdapter = null;
    
    private ActListAdapter actListAdapter = null;
    private FlowIndicator flowIndicator = null;
    private Timer mTimer = null;
    
    private String TAG = "ChannelActivity";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.channel_activity);
        prepareView();
        
        mTimer = new Timer();
        mTimer.scheduleAtFixedRate(new GallaryTask(), 0, 3000);
        
		getCategories();
    }
    
    private class GallaryTask extends TimerTask {
        @Override
        public void run() {
            mHandler.sendEmptyMessage(Config.SCROLL_ACTION);
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case Config.SCROLL_ACTION:
                    MotionEvent e1 = MotionEvent.obtain(SystemClock.uptimeMillis(),
                            SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN,
                            89.333336f, 265.33334f, 0);
                    MotionEvent e2 = MotionEvent.obtain(SystemClock.uptimeMillis(),
                            SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
                            300.0f, 238.00003f, 0);

                    mGallery.onFling(e1, e2, -1300, 0);
                    break;

                default:
                    break;
            }
        }
    };


    private void prepareView() {
    	act_list = (ListView)findViewById(R.id.act_list);
    	
    	LayoutInflater inflater = LayoutInflater.from(this);
    	
    	View act_list_header = inflater.inflate(R.layout.header_view, null);
    	
    	mGallery = (Gallery)act_list_header.findViewById(R.id.home_gallery);
    	flowIndicator = (FlowIndicator)act_list_header.findViewById(R.id.myView);
    	
    	mGalleryAdapter = new GalleryAdapter(this);
    	flowIndicator.setCount(mGalleryAdapter.getCount());
    	
    	mGallery.setAdapter(mGalleryAdapter);
    	
    	act_list.addHeaderView(act_list_header);
    	
    	mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                // TODO Auto-generated method stub
            	flowIndicator.setSeletion(arg2);
            }

            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });
    	
    	act_list.setOnItemClickListener(onItemClickListener);
    	
    }
    
    private OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			
		}
    	
	};
    
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case 0:
				findViewById(R.id.cat_progress).setVisibility(View.GONE);
				Bundle bundle = (Bundle)msg.obj;
				System.err.println(bundle.getString("info"));
				if(bundle.getString("flag").equals("ok"))
				{
					try {
						actListAdapter = new ActListAdapter(Parser.getCatsFromJson(bundle.getString("cats")));
						act_list.setAdapter(actListAdapter);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				break;
			case 1:
				
				break;
			default:
				break;
			}
			
		}
		
	};
	
	private WYRequestListener catRequestListener = new WYRequestListener() {
		
		@Override
		public void onException(Exception e) {
			// TODO Auto-generated method stub
			Log.i(TAG, "onException"+e.getMessage());
		}
		
		@Override
		public void onError(Error e) {
			// TODO Auto-generated method stub
			Log.i(TAG, "onError:"+e.getMessage());
		}
		
		@Override
		public void onComplete(Bundle bundle) {
			// TODO Auto-generated method stub
			handler.obtainMessage(0,bundle).sendToTarget();
		}
		
		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			Log.i(TAG, "onCancel");
		}

		@Override
		public void onStart() {
			// TODO Auto-generated method stub
			handler.obtainMessage(1).sendToTarget();
		}
	};
    
    private void getCategories()
    {
    	WYParams params = new WYParams();
		params.setAction("Http://125.216.245.70/wy/");
		params.add("action", "Cat_Get");
		new HttpTask(catRequestListener).execute(params);
    }
    
    
    private class ActListAdapter extends BaseAdapter
    {
    	
    	private List<Category> list = null;
    	
    	public ActListAdapter(List<Category> list)
    	{
    		this.list = list;
    	}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if(arg1==null)
			{
				holder = new ViewHolder();
				arg1 = LayoutInflater.from(getApplicationContext()).inflate(R.layout.cat_list_item, null);
				holder.cat_slug = (TextView)arg1.findViewById(R.id.cat_slug);
				holder.cat_title = (TextView)arg1.findViewById(R.id.cat_title);
				holder.cat_logo = (ImageView)arg1.findViewById(R.id.cat_logo);
				arg1.setTag(holder);
			}else{
				holder = (ViewHolder)arg1.getTag();
			}
			
			holder.cat_title.setText(list.get(arg0).getCat_name());
			holder.cat_slug.setText(list.get(arg0).getSlug());
			
			try {
				holder.cat_logo.setImageBitmap(BitmapFactory.decodeStream(getResources().getAssets().open("cat_"+list.get(arg0).getCat_id()+".png")));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return arg1;
		}
		
		private class ViewHolder
		{
			public TextView cat_title;
			public TextView cat_slug;
			public ImageView cat_logo;
		}
    	
    }
}
